from django.shortcuts import render

# Create your views here.

from rest_framework import status  # 记录一些状态码
from rest_framework.decorators import api_view  # 对函数的装饰器
from rest_framework.response import Response  #

from blog.models import Article
from blog.serializers import ArticleSerializer


@api_view(['GET', 'POST'])  # 1. 扩展了request， 2. 和传统的view函数进行区分
def article_list(request, format=None):
    """
    List all articles, or create a new article.
    """
    if request.method == 'GET':
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ArticleSerializer(data=request.data)
        if serializer.is_valid():
            # Very important. Associate request.user with author， 非常重要， 让当前用户和文章帮顶
            serializer.save(
                author=request.user)  # 由于序列化器中author是read-only字段，用户是无法通过POST提交来修改的，我们在创建Article实例时需手动将author和request.user绑定，如下所示：
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def article_detail(request, pk, format=None):  # 为了充分利用我们的响应不再与单一内容类型连接
    """
    Retrieve，update or delete an article instance。
    单个文章的操作
    """
    try:
        article = Article.objects.get(pk=pk)
    except Article.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ArticleSerializer(article)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ArticleSerializer(article, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        article.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
